package net.oschina.parse;

import net.oschina.db.SQL;
import net.oschina.spider.Fetch;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.sql.SQLException;
import java.util.*;


/**
 * Created by rex on 2015/3/9.
 */
public class Parser {
    SQL sql;

    public Parser(SQL sql) {
        this.sql = sql;
    }

    /**
     * parse user list
     * @param page
     * @param location
     * @param attach
     * @return total user number
     */
    public int ParseList(int page, String location, String attach){
        Fetch f = new Fetch();
        String listStr = f.GetList(page, location, attach);

        JSONObject jsonObj = null;
        try{
            jsonObj = new JSONObject(listStr);
        }catch (Exception e){
            System.out.println("[W] string is not json.");
            return 0;
        }

        JSONArray items = jsonObj.getJSONArray("items");
        int total = jsonObj.getInt("total_count");
        System.out.println("[i] total user " + total);

        for (int i = 0; i < items.length(); i++) {
            JSONObject user = (JSONObject)items.get(i);
            String username = (String)user.get("login");
            System.out.println("[username] "+username);

            sql.AddUser(username);
        }

        return total;

    }

    public void ParseUser(String username){
        String email = null;
        Fetch f = new Fetch();
        String userinfo = f.GetUser(username);

        JSONObject jsonObj = new JSONObject(userinfo);
        if (jsonObj.isNull("email")){
            email = "NOT EXIST";
        }else{
            email = jsonObj.getString("email");
            if (email.length()==0){
                email = "NOT EXIST";
            }
        }

        sql.UpdateEmail(username, email, userinfo);
    }

    /**
     * parse email from html page via regexp
     * @param username username
     */
    public void ParseUserEmailFromPage(String username){
        Fetch f = new Fetch();
        String email = f.GetUserEmail(username);

        if(email.length() == 0){
            email = "NOT EXIST";
        }

        System.out.println("[U]" + username + " / " + email);
        sql.UpdateEmail(username, email, "");
    }

    /**
     * get total user number for commandline
     * @param location
     * @return
     */
    public int ParseUserNumber(String location){
        Fetch f = new Fetch();
        String content = f.GetNumber(location);
        JSONObject jsonObj = new JSONObject(content);
        return jsonObj.getInt("total_count");
    }

}
